<?php
/**
 * Created by PhpStorm.
 * User: Jerry
 * Date: 2017/2/24
 * Time: 16:57
 */

namespace SDXApi\Service;
use SDXApi\Abstracts\TemplateAbstract;
use SDXApi\Model\SearchHotModel;


/**
 * Class HomeTemplateSearchAddressService
 * @package SDXApi\Service
 */
class HomeTemplateSearchAddressService extends TemplateAbstract
{
    /**
     * @var SearchHotModel
     */
    protected $searchHotModel;

    /**
     * HomeTemplateSearchAddressService constructor.
     */
    public function __construct()
    {
        $this->searchHotModel = new SearchHotModel();
    }

    /**
	 * Created by Jerry
	 * @param array $stencil
	 * @param int $userId
	 * @param int $wid
	 * @return array
	 */
	public function handle($stencil = array(), $userId = 0, $wid = 8)
	{
        return $data = $this->formatData($stencil);
	}

    /**
     * Created by Jerry
     * @param $stencil
     * @return mixed
     */
    protected function formatData($stencil)
    {
        $hots = $this->searchHotModel->get_search_hots();

        if (empty($hots)) {
            $hots = array();
        }
        else{
            $hots = self::shuffleAssoc($hots);
            $hots = array_merge($hots);
        }

        $stencil['search_data'] = $hots;

        return $stencil;
    }

    /**
     * 打乱二维数组
     * Created by Jerry
     * @param $list
     * @return array
     */
    static protected function shuffleAssoc($list)
    {
        if (! is_array($list)) {
            return $list;
        }

        $keys = array_keys($list);
        shuffle($keys);

        $random = array();
        foreach ($keys as $key) {
            $random[$key] = $list[$key];
        }

        return $random;
    }
}